package net.bblot.lottery.util;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.Toast;

import com.google.gson.Gson;

import net.bblot.lottery.activity.AppManager;
import net.bblot.lottery.activity.BaseDroidGapActivity;
import net.bblot.lottery.api.ApiClinet;
import net.bblot.lottery.api.SimpleResponseListener;
import net.bblot.lottery.api.request.GetIp;
import net.bblot.lottery.api.result.ExcuterResult;
import net.bblot.lottery.api.task.HttpTask;
import net.bblot.lottery.util.WifiAutoConnectManager.WifiCipherType;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class WifiUtil {
	public static boolean isSearching = false;
	private static Runnable runnable;

	/**
	 * 
	 * @param context
	 * @param isUserClick
	 *            是否用户主动点击
	 */
	public static void serchWifi(final BaseDroidGapActivity context, boolean isUserClick) {
		// connect(context, "lottery", "da8ab12345",
		// WifiCipherType.WIFICIPHER_WPA);
		if (isSearching) {
			return;
		}
		isSearching = true;
		List<ScanResult> enableResults = new ArrayList<ScanResult>();
		List<ScanResult> results = getWifiList(context);
		Logger.e("WifiUtil", results.toString());
		if (results != null && results.size() > 0) {
			for (int i = 0; i < results.size(); i++) {
				Logger.e("WifiUtil", results.get(i).SSID);
				if (results.get(i).SSID.contains("体彩云")) {
					enableResults.add(results.get(i));
				}
			}
		}
		if (enableResults.isEmpty()) {
			Toast.makeText(context, "未发现免费的wifi热点", Toast.LENGTH_SHORT).show();
			isSearching = false;
		} else {// 自动链接wifi则判断网络情况，如果当前连接不为wifi
			final String ssid = enableResults.get(0).SSID;
			if (!isWiFiActive(context) || !getWifiSsid(context.getApplicationContext()).contains(ssid)) {
				showWifiConnectDialog(context, ssid, false);
			} else {
				final AlertDialog aDialog = showGetAuthInfoDilog(context);
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						SimpleResponseListener simpleResponseListener = new SimpleResponseListener() {
							@Override
							public void onGetResult(String responsCode, ExcuterResult er) {
								// TODO Auto-generated method stub
								super.onGetResult(responsCode, er);
								try {
									if (aDialog != null && aDialog.isShowing())
										aDialog.dismiss();
								} catch (Exception e) {
									// TODO: handle exception
								}
								String result = er.getResult();
								if (GetIp.isAuth(result)) {
									ToastUtill.showToast(context, "“" + ssid + "”已连接成功！");
									isSearching = false;
								} else {
									Gson gson = new Gson();
									String ipParm = null;
									String jump_wifi_auth = null;
									GetIp.Result ipResult = null;
									try {
										ipResult = gson.fromJson(result, GetIp.Result.class);
									} catch (Exception e) {
										// TODO: handle exception
									}

									if (ipResult != null && ipResult.isOk()) {
										try {
											jump_wifi_auth = GetIp.IpParm.toWifiQurrayParm(ipResult.ap_info);
										} catch (Exception e) {
											// TODO Auto-generated catch
											// block
											e.printStackTrace();
										}
									} else {
										ipParm = GetIp.parseFromAuthIfo(result);
										try {
											jump_wifi_auth = GetIp.IpParm.toWifiQurrayParm(ipParm);
										} catch (Exception e) {
											// TODO Auto-generated catch
											// block
											e.printStackTrace();
										}
									}

									if (!TextUtils.isEmpty(jump_wifi_auth)) {
										try {
											// Logger.e("84", jump_wifi_auth);
											showWifiConnectDialog(context, ssid, false);
										} catch (Exception e) {
											// TODO Auto-generated catch
											isSearching = false;
											showWifiConnectDialog(context, ssid, true);
											e.printStackTrace();
										}
									} else {
										showWifiConnectDialog(context, ssid, false);
										isSearching = false;
									}
								}

							}

							@Override
							public void onWrongResponse(String responsCode, ExcuterResult er) {
								// TODO Auto-generated method stub
								aDialog.dismiss();
								isSearching = false;
								showWifiConnectDialog(context, ssid, true);
								super.onWrongResponse(responsCode, er);
							}
						};

						if (getWifiSsid(context.getApplicationContext()).contains(ssid)) {
							try {
								// ToastUtill.showToast(context, "正在获取认证信息");
								HttpTask httpTask = GetIp.getAuth(context, getLocalMacAddressFromIp(context),
										simpleResponseListener);
								ApiClinet.getInstance().doHttpTask(httpTask, simpleResponseListener);
							} catch (Exception e) {
								e.printStackTrace();
								isSearching = false;
								showWifiConnectDialog(context, ssid, true);
							}

						} else {
							isSearching = false;
							showWifiConnectDialog(context, ssid, true);
						}
					}
				}, 1000);

			}
		}

	}

	public static void showWifiConnectDialog(final BaseDroidGapActivity activity, final String ssid,
			final boolean isReAuth) {
		String message = "是否链接“" + ssid + "”上网？";
		String str_Positive = "免费接入";
		final long delay_time;
		if (isReAuth) {
			message = "获取WiFi认证超时失败... 是否重新连接？";
			str_Positive = "重新连接";
			delay_time = 100;
		} else {
			delay_time = 5000;
		}
		ProgressDialog.Builder builder = new ProgressDialog.Builder(activity).setTitle("提示").setMessage(message)
				.setNegativeButton("取消", null).setPositiveButton(str_Positive, new OnClickListener() {
					private int retry;

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						if (!getWifiSsid(activity.getApplicationContext()).contains(ssid)) {
							connect(activity, ssid, "", WifiCipherType.WIFICIPHER_NOPASS);
						}
						final Handler handler = new Handler();
						retry = 0;
						handler.postDelayed(runnable = new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								SimpleResponseListener simpleResponseListener = new SimpleResponseListener() {
									@Override
									public void onGetResult(String responsCode, ExcuterResult er) {
										// TODO Auto-generated method stub
										super.onGetResult(responsCode, er);
										String result = er.getResult();
										// Logger.e("WifiUtil", "185" + result +
										// "");
										if (GetIp.isAuth(result)) {
											ToastUtill.showToast(activity, ssid + "已认证");
										} else {
											Gson gson = new Gson();
											String ipParm = null;
											String jump_wifi_auth = null;
											GetIp.Result ipResult = null;
											try {
												ipResult = gson.fromJson(result, GetIp.Result.class);
											} catch (Exception e) {
												// TODO: handle exception
											}

											if (ipResult != null && ipResult.isOk()) {
												try {
													jump_wifi_auth = GetIp.IpParm.toWifiQurrayParm(ipResult.ap_info);
												} catch (Exception e) {
													// TODO Auto-generated catch
													// block
													e.printStackTrace();
												}
											} else {
												ipParm = GetIp.parseFromAuthIfo(result);
												try {
													jump_wifi_auth = GetIp.IpParm.toWifiQurrayParm(ipParm);
												} catch (Exception e) {
													// TODO Auto-generated catch
													// block
													e.printStackTrace();
												}
											}

											if (!TextUtils.isEmpty(jump_wifi_auth)) {
												try {
													Logger.e("84", jump_wifi_auth);
													activity.webInvoke.loadUrl(jump_wifi_auth);
													// activity.loadUrl(
													// "file:///android_asset/www/android.html"
													// + jump_wifi_auth);
												} catch (Exception e) {
													// TODO Auto-generated catch
													retry++;
													if (retry <= 1) {
														if (runnable != null) {
															handler.postDelayed(runnable, 3000);
														}
													} else {
														ToastUtill.showToast(activity, "认证超时，请稍候再试");
														runnable = null;
													}

												}
											} else {
												retry++;
												if (retry <= 1) {
													if (runnable != null) {
														handler.postDelayed(runnable, 3000);
													}
												} else {
													ToastUtill.showToast(activity, "认证超时，请稍候再试");
													runnable = null;
												}
											}
										}
									}

									@Override
									public void onWrongResponse(String responsCode, ExcuterResult er) {
										// TODO Auto-generated method stub
										retry++;
										if (retry <= 1) {
											if (runnable != null) {
												handler.postDelayed(runnable, 3000);
											}
										} else {
											ToastUtill.showToast(activity, "认证超时，请稍候再试");
											runnable = null;
										}
										super.onWrongResponse(responsCode, er);
									}
								};

								if (getWifiSsid(activity.getApplicationContext()).contains(ssid)) {
									try {
										ToastUtill.showToast(activity, "正在获取认证信息");
										HttpTask httpTask = GetIp.getAuth(activity, getLocalMacAddressFromIp(activity),
												simpleResponseListener);
										ApiClinet.getInstance().doHttpTask(httpTask, simpleResponseListener);
									} catch (Exception e) {
										e.printStackTrace();
										runnable = null;
										ToastUtill.showToast(activity, "认证失败，请稍候再试");
									}

								} else {
									runnable = null;
									ToastUtill.showToast(activity, "认证失败，请稍候再试");
								}
							}
						}, delay_time);
					}
				});
		AlertDialog pDialog = builder.create();
		pDialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				// TODO Auto-generated method stub
				isSearching = false;
			}
		});
		if (AppManager.getAppManager().isActivityAlive(activity.getClass())) {
			try {
				pDialog.show();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

	}

	public static AlertDialog showGetAuthInfoDilog(final BaseDroidGapActivity activity) {
		ProgressDialog pDialog = new ProgressDialog(activity);
		pDialog.setMessage("正在获取WiFi认证信息");
		if (AppManager.getAppManager().isActivityAlive(activity.getClass()))
			try {
				pDialog.show();
			} catch (Exception e) {
				// TODO: handle exception
			}
		return pDialog;
	}

	public static void connect(Context context, String ssid, String password, WifiCipherType type) {
		WifiManager wi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		WifiAutoConnectManager wManager = new WifiAutoConnectManager(wi);
		wManager.connect(ssid, password, type);
	}

	public static String getWifiState(Context context) {
		String ssid = "";
		WifiManager wi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		if (wi.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
			WifiInfo wifiInfo = wi.getConnectionInfo();
			ssid = wifiInfo.getSSID();
		}
		return ssid;
	}

	public static String getWifiSsid(Context context) {
		String ssid = "";
		WifiManager wi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wi.getConnectionInfo();
		ssid = wifiInfo.getSSID();
		return ssid;
	}

	public static List<ScanResult> getWifiList(Context context) {
		WifiManager wi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		wi.startScan();
		if (!wi.isWifiEnabled()) {
			wi.setWifiEnabled(true);
		}
		List<ScanResult> scanResults = wi.getScanResults();
		return scanResults;
	}

	public static boolean isWiFiActive(Context inContext) {
		Context context = inContext.getApplicationContext();
		ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getTypeName().equals("WIFI") && info[i].isConnected()) {
						return true;
					}
				}
			}
		}
		return false;
	}

	// 根据IP获取本地Mac
	public static String getLocalMacAddressFromIp(Context context) throws Exception {
		String mac_s = "";
		try {
			byte[] mac;
			ArrayList<String> ip_array = getLocalIpAddress();
			if (ip_array != null && ip_array.size() > 0) {
				for (int i = 0; i < ip_array.size(); i++) {
					NetworkInterface ne = NetworkInterface.getByInetAddress(InetAddress.getByName(ip_array.get(i)));
					mac = ne.getHardwareAddress();
					if (mac_s.length() > 1) {
						mac_s = mac_s + "," + byte2hex(mac);
					} else {
						mac_s = byte2hex(mac);
					}

				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return mac_s.trim();
	}

	public static ArrayList<String> getLocalIpAddress() {
		ArrayList<String> ip_array = new ArrayList<String>();
		String hostIp = null;
		try {
			Enumeration nis = NetworkInterface.getNetworkInterfaces();
			InetAddress ia = null;
			while (nis.hasMoreElements()) {
				NetworkInterface ni = (NetworkInterface) nis.nextElement();
				Enumeration<InetAddress> ias = ni.getInetAddresses();
				while (ias.hasMoreElements()) {
					ia = ias.nextElement();
					if (ia instanceof Inet6Address) {
						continue;// skip ipv6
					}
					String ip = ia.getHostAddress();
					if (!"127.0.0.1".equals(ip)) {
						if (!ip_array.contains(ip)) {
							ip_array.add(ip);
						}
						hostIp = ia.getHostAddress();

						// break;
					}
				}
			}
		} catch (SocketException e) {
			Logger.i("yao", "SocketException");
			e.printStackTrace();
		}
		Logger.i("yao432", "hostIp" + hostIp);
		return ip_array;
	}

	public static String byte2hex(byte[] b) {
		StringBuffer hs = new StringBuffer(b.length);
		String stmp = "";
		int len = b.length;
		for (int n = 0; n < len; n++) {
			stmp = Integer.toHexString(b[n] & 0xFF);
			if (stmp.length() == 1)
				hs = hs.append("0").append(stmp);
			else {
				hs = hs.append(stmp);
			}
		}
		return String.valueOf(hs);
	}

	/**
	 * 获取wifi  mac地址
	 * @param ctx
	 * @return
	 */
	public static String getWifiMac(Context ctx) {
		WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		String str = info.getMacAddress();
		if (str == null) str = "";
		return str;
	}
}
